package com.zzptc.myk.myapplication.ui.dashboard;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.zzptc.myk.myapplication.Adapter.BookAdapter;
import com.zzptc.myk.myapplication.Bean.Book;
import com.zzptc.myk.myapplication.Bean.ChooseBook;
import com.zzptc.myk.myapplication.R;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class DashboardFragment extends Fragment {
    private ListView chooselv;
    List<Book> bookList =new ArrayList<>();
    BookAdapter adapter;
    List<ChooseBook> chooseBookList=new ArrayList<>();
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
        initData();
        intitView(view);
        setListener();
        return view;
    }

    private void setListener() {
        chooselv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                int cid = chooseBookList.get(position).getId();
                LitePal.delete(ChooseBook.class,cid);
                chooseBookList.remove(id);
                bookList.remove(id);
                adapter.notifyDataSetChanged();;
                showToast("删除成功");

                return false;
            }
        });
    }

    private void initData() {
        SharedPreferences sp=getActivity().
                getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        int uid=sp.getInt("userid",-1);
        chooseBookList= LitePal.
                where("userid=?",uid+"").find(ChooseBook.class);
        for (ChooseBook c:chooseBookList){
             for (Book b:LitePal.findAll(Book.class)){
                if (b.getId()==c.getKookid()){
                    bookList.add(b);
                }
            }
        }
    }

    private void intitView(View view) {
        chooselv=view.findViewById(R.id.chooselv);
        adapter=new BookAdapter(getContext(),R.layout.book,bookList);
        chooselv.setAdapter(adapter);
    }
    private void showToast(String str){
        Toast.makeText(getContext(),str,Toast.LENGTH_SHORT).show();
    }
}